package com.dcits.mvc.common.controller;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.dcits.business.server.ServerType;
import com.dcits.business.server.ViewServerInfo;
import com.dcits.business.userconfig.UserSpace;
import com.dcits.constant.ConstantReturnCode;
import com.dcits.mvc.base.BaseController;
import com.dcits.mvc.common.model.ServerInfo;
import com.dcits.mvc.common.service.ServerInfoService;
import com.dcits.tool.StringUtils;
import com.jfinal.aop.Clear;
import com.jfinal.core.ActionKey;


public class ServerInfoController extends BaseController {
	
	private static final Logger logger = Logger.getLogger(ServerInfoController.class);
	private static ServerInfoService serverInfoService = new ServerInfoService();
	
	
	@Clear
	@ActionKey("/index")
	public void index() {
		render("/login.html");
	}
	
	public void edit() {
		ServerInfo serverInfo = getModel(ServerInfo.class, "", true);
		if (serverInfoService.checkRepeat(serverInfo) != null) {
			renderError(ConstantReturnCode.VALIDATE_FAIL, "该信息已存在,请搜索确认之后再添加!");
			return;
		}				
		serverInfoService.edit(serverInfo);
		//更新正在监控的服务器基本信息
		UserSpace.getUserSpace(getPara("userKey")).updateBaseInfo(serverInfo.getId(), serverInfo);
		renderSuccess(serverInfo, "");
	}
	
	public void get() {
		renderSuccess(serverInfoService.findById(getParaToInt("id")), "");
	}
	
	public void batchDelete() {
		serverInfoService.batchDelete(getPara("ids"));
		renderSuccess(null, "删除成功");
	}
	
	public void listAll() {
		String serverType = getPara("serverType");
		renderSuccess(serverInfoService.listAll(serverType), "");
	}
	
	public void del() {
		serverInfoService.deleteById(getParaToInt("id"));
		renderSuccess(null, "删除成功");
	}
	
	/**
	 * 开启监控
	 * @throws Exception 
	 */
	public void monitoring() throws Exception {
		ServerInfo info = serverInfoService.findById(getParaToInt("id"));
		ViewServerInfo serverInfo = (ViewServerInfo) ServerType.typeClasses.get(info.getServerType()).newInstance();
		serverInfo.setBaseServerInfo(info);
		
		String flag = serverInfo.connect();
		if (!"true".equals(flag)) {
			renderError(ConstantReturnCode.SERVER_CONNECT_FAILED, flag);
			return;
		} 
		
		serverInfo.getMonitoringInfo();
		
		//更新最后一次使用时间
		serverInfoService.updateLastTime(info);
		
		UserSpace.getUserSpace(getPara("userKey")).getServers().get(info.getServerType()).add(serverInfo);
		
		renderSuccess(null, "启动监控成功!");		
	}
	
	/**
	 * 批量添加
	 */
	public void batchSave() {
		int successCount = 0;
		int failCount = 0;
		
		String serverType = getPara("serverType");
		String infos = getPara("infos");
		String[] info = null;
		for (String str:infos.split("\\n")) {
			info = str.split(",|，"); 
			if (info.length < 5) {
				failCount++;
				continue;
			}
			
			//登录IP,真实IP,端口,用户名,密码,标签,附加参数
			//前6位为基本信息，后面全部为附加参数
			String tags = "";
			if (info.length > 5) {
				tags = info[5];
			}
			Map<String, String> extraParamsMap = new HashMap<String, String>();
			Class<?> clazz = ServerType.parameterClasses.get(serverType.toLowerCase());
			Field[] fields = clazz.getDeclaredFields();					
			for (int i = 0;i < fields.length;i++) {
				try {
					extraParamsMap.put(fields[i].getName(), info[6 + i]);
				} catch (Exception e) {
					// TODO: handle exception
					extraParamsMap.put(fields[i].getName(), "");
				}
				
			}
			
			ServerInfo serverInfo = new ServerInfo();
			serverInfo.setHost(info[0].trim());
			serverInfo.setRealHost(info[1].trim());
			serverInfo.setPort(StringUtils.isNotEmpty(info[2].trim()) ? Integer.valueOf(info[2].trim()) : 22);
			serverInfo.setUsername(info[3]);
			serverInfo.setPassword(info[4]);
			serverInfo.setTags(tags);
			serverInfo.setParameters(JSONObject.toJSONString(extraParamsMap));
			serverInfo.setCreateTime(new Date());
			serverInfo.setServerType(serverType);
			
			serverInfoService.edit(serverInfo);
			
			successCount++;
		}
		
		Map<String, Integer> countInfo = new HashMap<String, Integer>();
		countInfo.put("successCount", successCount);
		countInfo.put("failCount", failCount);
		renderSuccess(countInfo, "操作成功!");
		
	}
	
	
}
